<template>
  <div>
    <h1>计算属性|侦听属性</h1>
    <!--
      computed：某个属性依赖其他属性计算得到
      watch：一个数据变化会影响多个属性的变化
    -->
    <div>乘数1：{{ number1 }} 乘数2: {{ number2 }} 乘积：{{ sum }}</div>
    <div>
      <p>姓：{{ firstName }}</p>
      <p>名：{{ lastName }}</p>
      <p>姓名：{{ fullName }}</p>
    </div>
    <button @click="modifyFullName">修改名称</button>
    <button @click="modifyFirstName">修改姓</button>
    <div>
      <div>
        <button @click="switchLanguage('en')">英文</button>
        <button @click="switchLanguage('ch')">中文</button>
      </div>
      <div>{{ zhangsan }}</div>
      <div>{{ lisi }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "demon7",
  data() {
    return {
      number1: 2,
      number2: 5,
      firstName: "李",
      lastName: "祥祥",
      language: "ch",
      // zhangsan: "张三",
      // lisi: "李四"
      zhangsan: "",
      lisi: ""
    };
  },
  // 计算属性
  computed: {
    sum() {
      return this.number1 * this.number2;
    },
    // fullName是一个函数
    // fullName() {
    //   return this.firstName + " " + this.lastName;
    // }
    // fullName是一个对象包含get和set方法
    fullName: {
      // 读取方法
      get() {
        return this.firstName + " " + this.lastName;
      },
      // 设置方法
      set(newValue) {
        let arr = newValue.split(" ");
        this.firstName = arr[0];
        this.lastName = arr[1];
      }
    }
  },
  // 侦听属性
  watch: {
    // 以属性名为名称的函数
    firstName(newValue) {
      this.fullName = newValue + " " + this.lastName;
    },
    lastName(newValue) {
      this.fullName = this.firstName + " " + newValue;
    },
    // 语言属性变化
    // language(newVal) {
    //   if (newVal === "en") {
    //     this.zhangsan = "zhangsan";
    //     this.lisi = "lisi";
    //   } else if (newVal === "ch") {
    //     this.zhangsan = "张三";
    //     this.lisi = "李四";
    //   }
    // }
    // 语言属性变化：对象
    language: {
      // 属性变化处理器
      handler(newVal) {
        console.log("language属性发生变化");
        if (newVal === "en") {
          this.zhangsan = "zhangsan";
          this.lisi = "lisi";
        } else if (newVal === "ch") {
          this.zhangsan = "张三";
          this.lisi = "李四";
        }
      },
      // 是否一开始加载就调用
      immediate: true
    }
  },
  methods: {
    modifyFullName() {
      // 调用set方法
      this.fullName = "张 三";
    },
    modifyFirstName() {
      this.firstName = "张";
    },
    switchLanguage(val) {
      this.language = val;
    }
  }
};
</script>
<style lang="stylus" scoped></style>
